import {Component, OnInit, ViewChild} from '@angular/core';
import {Router} from '@angular/router';
import {ModalDirective} from 'ngx-bootstrap';
import {adSystemApiUrl} from '../../../../config/api';
import {HttpService} from '../../../lib/service/http.service';

@Component({
    selector: 'app-category',
    templateUrl: 'category.component.html',
    styleUrls: ['category.component.scss']
})
export class CategoryComponent implements OnInit {


    firLevel = [];
    secLevel = [];
    firId: number;
    secId: number;
    addFirName: string; // 增加一级类目名称
    addSecName: string; // 增加二级类目名称

    type: string;
    message: string;
    isShow = false;

    constructor(private httpService: HttpService) {}

    ngOnInit() {
      this.getClassList(0, 'firLevel');
    }

    // 获取类型列表
    getClassList(parent_id, container) {
      const url = `${adSystemApiUrl}/v1/admin/account/getClassByParent?parent_id=${parent_id}`;
      return this.httpService.httpPostAuth(url, '').subscribe(
        res => {
          if (res.code === 2000) {
            this[container] = res.data;
          } else {
            this.type = 'error';
            this.message = res.message;
            this.isShow = true;
          }
        }
      )
    }

  // 选中类目
  chosedCategory(level: number, id: number) {
    if (level === 0) {
      this.firId = id;
      this.secId = 0;
      this.getClassList(id, 'secLevel');
    } else {
      this.secId = id;
    }
  }

  // 添加类目
  addCategory(level: number) {
    if (level === 0) {
      if (!this.addFirName) {
        this.type = 'info';
        this.message = '请输入类目名称';
        this.isShow = true;
      } else {
        this.addCategorySubmit(this.addFirName, 0);
      }
    } else {
      if (!this.addSecName) {
        this.type = 'info';
        this.message = '请输入类目名称';
        this.isShow = true;
        return;
      }
      if (!this.firId) {
        this.type = 'info';
        this.message = '请先选择一级类目';
        this.isShow = true;
        return;
      }
      this.addCategorySubmit(this.addSecName, this.firId);
    }
  }

  // 添加类目
  addCategorySubmit(class_name: string, parent_id: number) {
    const url = `${adSystemApiUrl}/v1/admin/account/add_class`;
    const data = {class_name: class_name, parent_id: parent_id};
    return this.httpService.httpPostAuth(url, data).subscribe(
      res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '添加类目成功';
          this.isShow = true;
          if (parent_id === 0) {
            this.addFirName = '';
            this.getClassList(0, 'firLevel');
          } else {
            this.addSecName = '';
            this.getClassList(this.firId, 'secLevel');
          }
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }
}
